package com.df.handler;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

//@Component
@Slf4j
public class FailureHandler {
    
    private final ExternalTaskClient client;
    
    public FailureHandler(ExternalTaskClient client) {
        this.client = client;
    }
    
    @PostConstruct
    public void subscribe() {
        client.subscribe("failure-topic")
            .handler(this::handleFailure)
            .open();
        
        log.info("订阅 failure-topic 成功");
    }
    
    private void handleFailure(ExternalTask externalTask, ExternalTaskService externalTaskService) {
        try {
            log.info("开始处理失败任务，任务ID: {}", externalTask.getId());
            
            // 获取流程变量
            String processInstanceId = externalTask.getProcessInstanceId();
            Object sqlInjectResult = externalTask.getVariable("sqlInjectResult");
            Object sqlInjectDetails = externalTask.getVariable("sqlInjectDetails");
            
            log.info("流程实例ID: {}, SQL注入结果: {}, 详情: {}", 
                    processInstanceId, sqlInjectResult, sqlInjectDetails);
            
            // 模拟失败处理逻辑
            log.info("执行失败处理业务逻辑...");
            Thread.sleep(1200); // 模拟处理时间
            
            // 设置输出变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("failureResult", "失败处理完成");
            variables.put("failureTime", System.currentTimeMillis());
            variables.put("finalStatus", "FAILURE");
            variables.put("errorMessage", "检测到SQL注入风险，已进行安全处理");
            
            // 完成任务
            externalTaskService.complete(externalTask, variables);
            
            log.info("失败处理任务完成，任务ID: {}", externalTask.getId());
            
        } catch (Exception e) {
            log.error("处理失败任务失败，任务ID: {}", externalTask.getId(), e);
            
            // 处理失败
            externalTaskService.handleBpmnError(externalTask, "FAILURE_ERROR", "失败处理失败: " + e.getMessage());
        }
    }
} 